package com.jhd.jiangxi.activity.main;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.app.ActivityCompat;

import com.alibaba.fastjson.JSON;
import com.jhd.jiangxi.R;
import com.jhd.jiangxi.ScanApplication;
import com.jhd.jiangxi.UtilHelper;
import com.jhd.jiangxi.service.VaccineService;
import com.jhd.jiangxi.util.ListString;
import com.jhd.jiangxi.vo.AuthToken;
import com.jhd.jiangxi.vo.DeptVo;
import com.jhd.jiangxi.vo.JsonForResult;
import com.jhd.jiangxi.vo.Login;
import com.jhd.jiangxi.vo.SN;

import net.zigin.commons.util.ParamsMapUtil;
import net.zigin.commons.util.StringUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

/*登录界面
 * 免疫云温州账号：wzAdmin 密码：123456
 * 审批流主键:  approvalId: AE84637DA7D211E6A9F000163E000137
 * 价格本主键:  priceBookMstId: 491E829F9A8711E7ABA000163E0D4F3D
 * 价格本编号：priceBookNo: 温州疾控价格本
 * 储位：storage：冷藏
 * */
public class LoginActivity extends BaseActivity {
    Button button = null;
    @BindView(R.id.checkbox)
    CheckBox checkbox;
    @BindView(R.id.et_Name)
    EditText et_Name;
    @BindView(R.id.et_Password)
    EditText et_Password;
    @BindView(R.id.tvTestVersion)
    TextView tvTestVersion;
    @BindView(R.id.btnLogin)
    Button btnLogin;
    private PopupWindow popup;
    private List<Login> logins;
    private ListView listView;

    @OnClick({R.id.btnLogin})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnLogin:
                String name = et_Name.getText().toString().trim();
                String password = et_Password.getText().toString().trim();
                if ("".equals(name) || "".equals(password)) {
                    UtilHelper.alertMsg(LoginActivity.this, "错误", "用户名和密码不能为空!");
                    DisplayMetrics metric = new DisplayMetrics();
                    getWindowManager().getDefaultDisplay().getMetrics(metric);
                    int screenHeight = metric.heightPixels;
                    return;
                }
                Retrofit retrofit = UtilHelper.retrofit(application, UtilHelper.baseUrls.API(application.getBackSystem()));//URL的头
                VaccineService vs = retrofit.create(VaccineService.class);
                Map<String, String> params = ParamsMapUtil.getInstance("username", name).addParam("password", password).addParam("type", "password");
                Call<JsonForResult> jsonForResultCall = vs.getAuthInfo(params);//调用接口获取json返回
                jsonForResultCall.enqueue(new LoginInfoCallback(name, password));
                break;
        }
    }

    @SuppressLint("MissingPermission")
    public String getSerialNumber() {
        String serial = "";
        //通过android.os获取sn号
        try {
            serial = android.os.Build.SERIAL;
            if (!serial.equals("") && !serial.equals("unknown")) return serial;
        } catch (Exception e) {
            serial = "";
        }

        //通过反射获取sn号
        try {
            Class<?> c = Class.forName("android.os.SystemProperties");
            Method get = c.getMethod("get", String.class);
            serial = (String) get.invoke(c, "ro.serialno");
            if (!serial.equals("") && !serial.equals("unknown")) return serial;

            //9.0及以上无法获取到sn，此方法为补充，能够获取到多数高版本手机 sn
            if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)serial = Build.getSerial();
        } catch (Exception e) {
            serial="";
        }
        return serial;
    }
    /*public void checkSN(){
        String sn=getSerialNumber();
        Retrofit retrofit = UtilHelper.retrofit(application, "http://192.168.1.145:9020/");//URL的头
        System.out.println(sn);
        VaccineService vs = retrofit.create(VaccineService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("sn", sn);
        Call<JsonForResult> jsonForResultCall = vs.validateSnIsLegal(params);//调用接口获取json返回
        jsonForResultCall.enqueue(new CheckSNCallback());
    }
    private class CheckSNCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    SN data = JSON.parseObject(jsonForResult.getData().toString(), SN.class);
                    if(!data.isResult()) {
                        finish();
                        Toast.makeText(LoginActivity.this,"设备未注册,无法使用!",Toast.LENGTH_LONG).show();
                    }
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null) {
                        alarm(jsonForResult.getMessage());
                        UtilHelper.alertMsg(LoginActivity.this, "错误", jsonForResult.getMessage());
                    }
                }
            } catch (Exception e) {
                UtilHelper.alertMsg(LoginActivity.this, "错误", e.getMessage());
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "对比SN错误!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(LoginActivity.this, "错误", msg);
        }
    }*/

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        //如果检查到不是测试版本,将该控件隐藏
        //checkSN();
        if ("0".equals(application.getBackSystem())) tvTestVersion.setVisibility(View.VISIBLE);
        if(application.getUserPass()!=null){
            logins = ListString.str2list(application.getUserPass());
            et_Password.setText(logins.get(0).getPassword());
            et_Name.setText(logins.get(0).getUser());
            listView = new ListView(this);
            listView.setDivider(null);//设置分割线
            listView.setVerticalScrollBarEnabled(false);//不显示滑动条
            listView.setAdapter(new MyAdapter());
        }
        /*如果没有聚焦,就聚焦时,弹窗,如果已经聚焦就点击监听*/
        et_Name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                popupWindow();
            }
        });
        et_Name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow();
            }
        });
    }

    /**
     * 显示窗口
     */
    @SuppressLint("ResourceAsColor")
    private void popupWindow(){
        popup = new PopupWindow(this);
        popup.setWidth(et_Name.getWidth());
        popup.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);
        popup.setBackgroundDrawable(getResources().getDrawable(android.R.color.white));
        popup.setContentView(listView);//设置显示内容
        popup.setOutsideTouchable(true);//点击PopupWindow以外的区域自动关闭该窗口
        popup.showAsDropDown(et_Name);//显示在edit控件的下面0,0代表偏移量
    }
    //适配器
    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return logins.size();
        }

        @Override
        public Object getItem(int position) {
            return position;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            HolderView holderView=null;
            if(convertView==null){
                convertView=View.inflate(getApplicationContext(), R.layout.item_dialog_login,null);
                holderView=new HolderView();
                holderView.text=(TextView) convertView.findViewById(R.id.tvStorage);
                convertView.setTag(holderView);
            }else{
                holderView=(HolderView) convertView.getTag();
            }
            holderView.text.setText(logins.get(position).getUser());
            //listview的单击事件
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    et_Name.setText(logins.get(position).getUser());
                    et_Password.setText(logins.get(position).getPassword());
                    Login login=new Login();
                    login.setPassword(et_Password.getText().toString().trim());
                    login.setUser(et_Name.getText().toString().trim());
                    List<Login> logins = ListString.str2list(application.getUserPass());
                    logins.remove(position);
                    logins.add(0,login);
                    String s=ListString.list2str(logins);
                    application.setUserPass(s);
                    popup.dismiss();//关闭窗口

                }
            });
            return convertView;
        }
        class HolderView{//由于这里用户都是同一个人,就省略用户图像的刷新
            private TextView text;
        }
    }


    //登录的回调接口
    private class LoginInfoCallback implements Callback<JsonForResult> {
        private String _name;
        private String _password;

        public LoginInfoCallback(String name, String password) {
            _name = name;
            _password = password;
        }

        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                if (response.code() > 400 && response.code() < 500) {
                    UtilHelper.alertMsg(LoginActivity.this, "错误", "用户名或密码错误!");
                    return;
                }
                JsonForResult jsonForResult = response.body();
                if (jsonForResult != null && jsonForResult.isSuccess()) {
                    //请求授权信息
                    AuthToken authToken = JSON.parseObject(jsonForResult.getData().toString(), AuthToken.class);
                    if (authToken == null || StringUtil.isNullOrEmpty(authToken.getAccessToken())) {
                        UtilHelper.alertMsg(LoginActivity.this, "错误", "请求授权信息失败");
                        return;
                    }
                    if(checkbox.isChecked()){
                        Login login=new Login();
                        login.setPassword(et_Password.getText().toString().trim());
                        login.setUser(et_Name.getText().toString().trim());
                        if(application.getUserPass()!=null){
                            List<Login> list=ListString.str2list(application.getUserPass());
                            if(!list.contains(login)){
                                list.add(0,login);
                                application.setUserPass(ListString.list2str(list));
                            }

                        }else{
                            List<Login> list=new ArrayList<>();
                            list.add(login);
                            application.setUserPass(ListString.list2str(list));
                        }
                    }
                    String accessToken = authToken.getAccessToken();
                    String deptId = authToken.getAccessTokenByKey("deptId").toString();
                    application.setAccessToken(accessToken);
                    application.setUserId(authToken.getAccessTokenByKey("userId").toString());
                    application.setUserName(_name);
                    application.setPassword(_password);
                    application.setDeptId(deptId);
                    getDepartment(application.getAccessToken(), deptId);//去获取deptName
                    application.isConfigEditor();//登录完将数据保存的shareperence配置好
                } else {
                    String msg = "";
                    if (jsonForResult == null) msg = "登录失败";
                    else msg = jsonForResult.getMessage();
                    UtilHelper.alertMsg(LoginActivity.this, "错误", msg);
                }
            } catch (Exception e) {
                UtilHelper.alertMsg(LoginActivity.this, "错误", e.getMessage());
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "登录失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) {
                if (t.getMessage().indexOf("400") >= 0) {
                    msg = "用户名或密码错误!";
                } else {
                    msg = msg + t.getMessage();
                }
            }
            UtilHelper.alertMsg(LoginActivity.this, "错误", msg);
        }
    }

    /*创建线程获取部门信息*/
    private void getDepartment(String token, String deptId) {
        String url = UtilHelper.baseUrls.UC(application.getBackSystem());
        Retrofit retrofit = UtilHelper.retrofit(url);//创建网络请求
        VaccineService vs = retrofit.create(VaccineService.class);
        Map<String, String> params = ParamsMapUtil.getInstance("deptId", deptId);
        Call<JsonForResult> jsonForResultCall = vs.getDepartmentById(token, params);
        jsonForResultCall.enqueue(new GetDepartmentCallback());
    }

    /*部门的回调接口*/
    private class GetDepartmentCallback implements Callback<JsonForResult> {
        @Override
        public void onResponse(Call<JsonForResult> call, Response<JsonForResult> response) {
            try {
                JsonForResult jsonForResult = (JsonForResult) response.body();
                if (jsonForResult != null && jsonForResult.isSuccess() && jsonForResult.getData() != null) {
                    DeptVo dept = JSON.parseObject(jsonForResult.getData().toString(), DeptVo.class);
                    application.setDeptName(dept.getName());
                    application.setDeptType(dept.getDeptType());
                    //setHistory();//将数据保存在本地,方便下次进入对比
                    Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();//登录成功,跳转到主界面,将登录界面destroy
                } else {
                    if (jsonForResult != null && jsonForResult.getMessage() != null) {
                        alarm(jsonForResult.getMessage());
                        UtilHelper.alertMsg(LoginActivity.this, "错误", jsonForResult.getMessage());
                    } else {
                        UtilHelper.alertMsg(LoginActivity.this, "错误", "获取部门信息失败,请通知管理员检查!");
                    }
                }
            } catch (Exception e) {
                UtilHelper.alertMsg(LoginActivity.this, "错误", e.getMessage());
            }
        }

        @Override
        public void onFailure(Call<JsonForResult> call, Throwable t) {
            String msg = "获取机构部门信息失败!";
            if (StringUtil.isNullOrEmpty(t.getMessage()) == false) msg = msg + t.getMessage();
            UtilHelper.alertMsg(LoginActivity.this, "错误", msg);
        }
    }
}
